package com.codebox.common.base;

import android.support.annotation.Nullable;

import com.bumptech.glide.load.HttpException;
import com.codebox.common.util.ToastUtils;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;

import static com.codebox.common.base.Status.ERROR;
import static com.codebox.common.base.Status.FAILURE;
import static com.codebox.common.base.Status.LOADING;
import static com.codebox.common.base.Status.SUCCESS;


/**
 * @author Able
 */
public class Resource<T> {

    public Status status;

    @Nullable
    public String message;

    @Nullable
    public T data;

    public Throwable error;

    public Resource(Status status, @Nullable T data, @Nullable String message) {
        this.status = status;
        this.data = data;
        this.message = message;
    }

    public Resource(Status status, Throwable t) {
        this.status = status;
        this.error = t;
    }

    public static <T> Resource<T> loading() {
        return new Resource<>(LOADING, null, null);
    }

    public static <T> Resource<T> loading(@Nullable T data) {
        return new Resource<>(LOADING, data, null);
    }

    public static <T> Resource<T> success(@Nullable T data) {
        return new Resource<>(SUCCESS, data, null);
    }

    public static <T> Resource<T> response(@Nullable BaseResult<T> data) {
        if (data != null) {
            if (data.isSuccess()) {
                return new Resource<>(SUCCESS, data.getData(), null);
            }
            return new Resource<>(FAILURE, null, data.getErrorMsg());
        }
        return new Resource<>(ERROR, null, null);
    }

    public static <T> Resource<T> failure(String msg) {
        return new Resource<>(FAILURE, null, msg);
    }

    public static <T> Resource<T> error(Throwable t) {
        showErrorMessage(t);
        return new Resource<>(ERROR, t);
    }

    private static void showErrorMessage(Throwable t) {
        if (t instanceof HttpException) {
            ToastUtils.showError("网路错误");
        } else if (t instanceof JsonParseException || t instanceof JSONException) {
            ToastUtils.showError("解析错误");
        } else if (t instanceof ConnectException) {
            ToastUtils.showError("连接错误");
        } else {
            ToastUtils.showError("错误：" + t.getMessage());
        }
    }

    @Override
    public String toString() {
        return "Resource{" +
                "status=" + status +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }

}
